﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Himp.Platform.Client.Models;
using Dapper;
using System.Configuration;

namespace Himp.Platform.Client.Dals
{
    /// <summary>
    /// 手工存样
    /// </summary>
    public class SamplePreparationRecDal : ISamplePreparationRecDal
    {
        #region SQL

        public const string EXIST_FLAG_SQL = @"
            SELECT CASE WHEN 
            EXISTS (SELECT 1 FROM [dbo].[HY_SamplePreparationRec] WHERE PackCode = @PackCode) 
            THEN 1 
            ELSE 0 
            END";

        public const string INSERT_SAMPLE_PREPARATION = @"
            INSERT INTO
            [dbo].[HY_SamplePreparationRec]
            (
            [MachineCode]
            ,[SampleID]
            ,[PackCode]
            ,[ZYWeight]
            ,[ZYType]
            ,[SampleType]
            ,[Size]
            ,[Water]
            ,[StartTime]
            ,[EndTime]
            ,[SampleWeight]
            ,[UserName]
            )
            VALUES
            (
            @MachineCode
            ,@SampleID
            ,@PackCode
            ,@ZYWeight
            ,@ZYType
            ,@SampleType
            ,@Size
            ,@Water
            ,@EndTime
            ,@EndTime
            ,@SampleWeight
            ,@UserName
            )
            ";

        public const string INSERT_STANDARD_TEST_TASK_SQL = @"
            INSERT INTO
            [TaskScheduling].[TS_StandardTestTasks]
            (
            SampleCode,
            TestCode,
            BottomCode,
            Sampletype,
            TaskType,
            SampeWay,
            TestCnt,
            TaskAssgnTime,
            LastOperTime,
            ExecStas
            )
            VALUES
            (
            @SampleCode,
            @TestCode,
            @BottomCode,
            @Sampletype,
            @TaskType,
            @SampeWay,
            @TestCnt,
            GETDATE(),
            GETDATE(),
            @ExecStas
            )
            ";

        #endregion

        #region 方法

        /// <summary>
        /// 手工制样存瓶
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task<string> HandleSamplePreparation(IEnumerable<SamplePreparationRecModel> datas)
        {
            //读取配置值
            string url = ConfigurationManager.AppSettings["DefaultConnect"];

            try
            {
                using (IDbConnection connection = new SqlConnection(url))
                {
                    connection.Open();

                    foreach (var data in datas)
                    {
                        // 检查 ID 是否已存在
                        bool exists = await connection.ExecuteScalarAsync<bool>(EXIST_FLAG_SQL,
                            new { data.PackCode });

                        if (!exists)
                        {
                            var codeStas = await connection.ExecuteAsync(INSERT_SAMPLE_PREPARATION, data);
                        }
                        else
                        {
                            return $"瓶底码:{data.PackCode}:已存在";
                        }

                        await CreateStandardTestTask(data);
                    }
                }
            }
            catch (Exception e)
            {
                return e.Message;
            }

            return string.Empty;
        }

        /// <summary>
        /// 生成标准化制样任务
        /// 2024-8-24
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task CreateStandardTestTask(SamplePreparationRecModel data)
        {
            string url = ConfigurationManager.AppSettings["DefaultConnect"];

            using (IDbConnection connection = new SqlConnection(url))
            {
                CodeConversionManager codeConversionManager = new CodeConversionManager();
                var samplingResult = codeConversionManager.GenerateTestingNo(data.SampleID, MainWindow.UserName);
                var testCode = data.SampleID;

                if (samplingResult.Item1)
                {
                    testCode = samplingResult.Item2;
                }

                if (data.SampleType == 1)
                {
                    var intStas = await connection.ExecuteAsync(INSERT_STANDARD_TEST_TASK_SQL,
                        new
                        {
                            SampleCode = data.SampleID,
                            TestCode = testCode,
                            BottomCode = data.PackCode,
                            Sampletype = "61",
                            TaskType = 0,
                            SampeWay = "自动",
                            TestCnt = 2,
                            ExecStas = "未就绪"
                        });
                    //_logger.LogInformation($"生成标准化验任务:{data.PackCode}:{intStas}");
                }
                else if (data.SampleType == 4)
                {
                    var intStas = await connection.ExecuteAsync(INSERT_STANDARD_TEST_TASK_SQL,
                        new
                        {
                            SampleCode = data.SampleID,
                            TestCode = testCode,
                            BottomCode = data.PackCode,
                            Sampletype = "21",
                            TaskType = 0,
                            SampeWay = "自动",
                            TestCnt = 2,
                            ExecStas = "未就绪"
                        });
                    //_logger.LogInformation($"生成标准化验任务:{data.PackCode}:{intStas}");
                }
            }
        }

        #endregion
    }
}
